package serversidepkg;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import backendpkg.DataSource;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

/**
 * Servlet implementation class CheckReqStatus
 */
public class CheckReqStatus extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckReqStatus() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			response.setHeader("Cache-Control","no-cache"); //Forces caches to obtain a new copy of the page from the origin server
			response.setHeader("Cache-Control","no-store"); //Directs caches not to store the page under any circumstance
			response.setDateHeader("Expires", 0); //Causes the proxy cache to see the page as "stale"
			response.setHeader("Pragma","no-cache"); //HTTP 1.0 backward compatibility
			
			//Get username from session
			HttpSession session = request.getSession();			
            String user = (String) session.getAttribute("username");

            if (user == null) {
               request.setAttribute("Error", "Session has ended.  Please login.");
               RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
               rd.forward(request, response);
            }else{
	            
	            //Get Parameters from request
	            String receiver = request.getParameter("receiver");
	            
	            //Get connection to database
	            DataSource datasource = new DataSource();
	            Connection conn = datasource.getConnection();
	            PreparedStatement statement;
	            
	            //Execute query in order to get state of request
	            String query = "SELECT * FROM Incoming WHERE receiver=? AND sender=?;";
	            statement = (PreparedStatement) conn.prepareStatement(query);
	            statement.setString(1, receiver);
	            statement.setString(2, user);
	            
	            ResultSet result = statement.executeQuery();          
	            
	            //Prepare xml string
	            String xml="<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?><root>";
	            String accepted = "NULL";
	            
	            while(result.next()){	
	                xml+="<request>";
	                xml+="<name>" + result.getString("receiver") + "</name>";
	                
	                if(result.getString("accepted")!=null)
	                	accepted = result.getString("accepted");
	                
	                if(accepted.equals("true") || accepted.equals("false")){
	                	//Delete from incoming
	                    String sql = "DELETE FROM Incoming WHERE receiver=? AND sender=?;";
	                    statement = (PreparedStatement) conn.prepareStatement(sql);
	                    statement.setString(1, receiver);
	                    statement.setString(2, user);
	                    statement.executeUpdate();  
	                }
	                
	                xml+="<accepted>" + accepted + "</accepted>";
	                xml+="<chat_id>" + result.getInt("newchatID")+ "</chat_id>";
	                xml+="</request>";
	            }
	
	            xml+="</root>";
	                            	
	            //System.out.println(xml);
	            response.getWriter().write(xml);
            }
        } catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {            
            
        }
	}

}
